package com.zsj.job;

import com.alibaba.fastjson.JSONObject;
import com.zsj.config.ConfigBean;
import com.zsj.config.ScheduledCondition;
import com.zsj.entity.RechargeResponse;
import com.zsj.enums.ReorderStatusEnum;
import com.zsj.mysql.entity.DyMobileRecharge;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.service.MobileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class ReorderJob {

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private IDyMobileRechargeService mobileRechargeService;

    @Autowired
    private MobileService mobileService;

    @Scheduled(cron = "0 */10 * * * ?")
    public void reorder() {
        if (!"true".equals(configBean.getBatchSwitch())) {
            log.info("批处理开关为:{}，不执行重发订单任务", configBean.getBatchSwitch());
            return;
        }
        log.info("开始执行重发订单任务");
        try {
            // 当前时间
            LocalDateTime now = LocalDateTime.now();
            // 查询待重发的起始时间
            LocalDateTime beginTime = now.minusHours(configBean.getReorderQueryTime());
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String begin = beginTime.format(timeFormatter);
            String end = now.format(timeFormatter);
            List<DyMobileRecharge> list = new ArrayList<>();
            // 遍历beginTime到now之间的每一天
            long daysBetween = ChronoUnit.DAYS.between(beginTime.toLocalDate(), now.toLocalDate());
            for (int i = 0; i <= daysBetween; i++) {
                String date = beginTime.plusDays(i).toLocalDate().format(dateFormatter);
                log.info("开始查询[{}]待重发订单的数据", date);
                list.addAll(mobileRechargeService.getNeedReorder4Job(date.substring(0, 6), date, configBean.getMaxReorderTimes(),
                        begin, end, configBean.getReorderQueryCount()));
            }

            log.info("待重发订单的数据量:{}", list.size());
            log.info("开始批量重发");
            for (DyMobileRecharge dmr : list) {
                RechargeResponse response = new RechargeResponse();
                try {
                    MDC.put("dyOrderNo", dmr.getChargeNo());
                    MDC.put("selfUid", dmr.getChannelChargeNo());
                    log.info("重发的订单:[{}]", JSONObject.toJSONString(dmr));
                    if (StringUtils.isBlank(dmr.getSupplierOrderNo())) {
                        mobileService.reorder(dmr, response);
                    } else {
                        log.info("订单:{}已经重发，无需再发送，供应商订单号:{}", dmr.getChannelChargeNo(), dmr.getSupplierOrderNo());
                        log.info("更新重发状态为重发成功");
                        boolean flag = mobileRechargeService.updateReorder(String.valueOf(dmr.getTxnDate()).substring(0, 6),
                                ReorderStatusEnum.SUCCESS.getCode(), null, dmr.getChargeNo());
                        log.info("更新重发状态结果:{}", flag);
                    }

                    Thread.sleep(5);
                } catch (Exception e) {
                    log.info("重发订单异常");
                    log.error("重发订单异常", e);
                } finally {
                    MDC.clear();
                }
            }
            log.info("批量重发完成");
        } catch (Exception e) {
            log.info("执行重发订单任务异常", e);
        }
        log.info("执行重发订单任务务结束");
    }
}
